#include "server.hpp"

void HandleClose(Channel *channel)
{
    std::cout << "close: " << channel->Fd() << std::endl;
    channel->Remove();
    delete channel;
}

void HandleRead(Channel *channel)
{
    int fd = channel->Fd();
    char buf[1024] = {0};
    int ret = recv(fd, buf, 1023, 0);
    if (ret < 0)
    {
        HandleClose(channel); // 关闭释放
    }
    channel->EnableWrite(); // 启动可读事件
    std::cout << buf << std::endl;
}

void HandleWrite(Channel *channel)
{
    int fd = channel->Fd();
    const char *data = "天气还不错！！";
    int ret = send(fd, data, strlen(data), 0);
    if (ret < 0)
    {
        return HandleClose(channel);
    }
    channel->DisableWrite(); // 关闭写监控
}

void HandleError(Channel *channel)
{
    return HandleClose(channel);
}

void HandleEvent(Channel *channel)
{
    std::cout << "有了一个事件\n";
}

void Accept(Poller *poller, Channel *lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    if (newfd < 0)
    {
        return;
    }
    Channel *channel = new Channel(poller, newfd);
    // 绑定回调函数
    channel->SetReadCallback(std::bind(HandleRead, channel));
    channel->SetWriteCallback(std::bind(HandleRead, channel));
    channel->SetCloseCallback(std::bind(HandleRead, channel));
    channel->SetErrorCallback(std::bind(HandleRead, channel));
    channel->SetEventCallback(std::bind(HandleRead, channel));
    channel->EnableRead();
}

// int main()
// {
//     Poller poller;
//     Socket lst_sock;
//     lst_sock.CreateServer(8500);
//     Channel channel(&poller, lst_sock.Fd());
//     channel.SetReadCallback(std::bind(Accept, &poller, &channel));
//     channel.EnableRead();
//     while (1)
//     {
//         int newfd = lst_sock.Accept();
//         if (newfd < 0)
//             continue;
//         Socket cli_sock(newfd);
//         char buf[1024] = {0};
//         int ret = cli_sock.Recv(buf, 1024);
//         if (ret < 0)
//         {
//             cli_sock.Close();
//             continue;
//         }
//         cli_sock.Send(buf, ret);
//         cli_sock.Close();
//     }
//     return 0;
// }

int main()
{
    Poller poller;
    Socket lst_sock;
    lst_sock.CreateServer(8500);
    Channel channel(&poller, lst_sock.Fd());
    channel.SetReadCallback(std::bind(Accept, &poller, &channel));
    channel.EnableRead();
    while (1)
    {
        std::vector<Channel *> actives;
        poller.Poll(&actives);
        for (auto &a : actives)
        {
            a->HandleEvent();
        }
    }
    lst_sock.Close();
    return 0;
}